<template>
    <div class="table-container">
        <el-table 
            ref="elTableRef" 
            :data="tableData" 
            :border="border" 
            :stripe="stripe" 
            :row-key="rowKey"
            :height="height + 'px'" 
            :max-height="height"
            :default-sort="defaultSort"
            :highlight-current-row="highlightCurrentRow" 
            :loading="loading"
            :row-class-name="stripe ? getRowClassName : null" 
            :size="size" 
            :header-cell-style="computedHeaderCellStyle"
            :header-cell-class-name="'custom-header-cell'"
            v-bind="tableProps" 
            tooltip-effect="dark"
            @selection-change="onSelectionChange" 
            @current-change="onCurrentChange" 
            @sort-change="onSortChange"
            @filter-change="onFilterChange"
            style="width: 100%;border-radius: 10px;"
        >
            <el-table-column 
                align="center" 
                v-if="selection" 
                type="selection" 
                :width="selectionWidth"
                :selectable="selectable" 
                :reserve-selection="reserveSelection" 
            />
            <!-- 处理序号列 -->
            <el-table-column 
                v-for="col in columns.filter(c => c.type === 'index')" 
                :key="'index-' + col.label" 
                v-bind="getColumnProps(col)"
                type="index"
                :index="col.indexMethod || ((index) => index + 1)"
            />
            <!-- 处理普通列 -->
            <el-table-column 
                v-for="col in columns.filter(c => !c.type || c.type !== 'index')" 
                :key="col.prop || col.label" 
                v-bind="getColumnProps(col)"
                :show-overflow-tooltip="true"
            >
                <template #default="scope">
                    <slot v-if="col.slot" :name="col.slot" v-bind="scope" />
                    <span v-else-if="col.render">{{ col.render(scope.row, col, scope.$index) }}</span>
                    <span v-else>{{ scope.row[col.prop] || '--' }}</span>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import {
    ref,
    defineProps,
    defineEmits,
    onMounted,
    onBeforeUnmount,
    nextTick,
    computed
} from '@vue/composition-api'

const props = defineProps({
    tableData: { type: Array, required: true }, // 表格数据源
    columns: { type: Array, required: true }, // 列数据
    selection: { type: Boolean, default: false }, // 是否出现选择项目
    single: { type: Boolean, default: false }, // 是否单选
    selectionWidth: { type: [String, Number], default: 55 }, // 选择项目宽度
    selectable: { type: Function }, // 选择项目是否可选
    reserveSelection: { type: Boolean, default: false }, // 是否保留选择项目
    radio: { type: Boolean, default: false }, // 是否出现单选项目
    radioWidth: { type: [String, Number], default: 55 }, // 单选项目宽度
    radioIndex: { type: Function, default: i => i + 1 }, // 单选项目索引
    rowKey: { type: String, default: 'id' }, // 行数据唯一标识
    height: { type: [String, Number], default: null }, // 表格高度
    border: { type: Boolean, default: true }, // 是否出现边框
    stripe: { type: Boolean, default: true }, // 是否隔行变色
    defaultSort: { type: Object, default: () => ({}) }, // 默认排序
    highlightCurrentRow: { type: Boolean, default: false }, // 是否高亮当前行
    loading: { type: Boolean, default: false }, // 是否加载中
    tableProps: { type: Object, default: () => ({}) }, // 表格属性
    stripeColor: { type: String, default: '#f8f8f8' }, // 隔行变色颜色
    size: { type: String, default: 'mini' },  // 尺寸大小 medium small mini
    headerBackgroundColor: { type: String, default: '#f5f5f5' }, // 表头背景颜色
    headerTextColor: { type: String, default: '#444' } // 表头文字颜色
})

const emit = defineEmits([
    'selection-change', // 选择项目变化
    'current-change',
    'sort-change',
    'radio-change',
    'loadScroll',
    'filter-change' // 添加筛选器变化事件
])

const elTableRef = ref(null)
let bodyWrapper = null
const selectedRows = ref([])
const isSingleSelecting = ref(false)

// 表头单元格样式计算属性
const computedHeaderCellStyle = computed(() => ({
    backgroundColor: props.headerBackgroundColor,
    color: props.headerTextColor,
    fontWeight: '600'
}))

// 过滤掉 slot 属性，避免与 el-table-column 冲突
const getColumnProps = (col) => {
    const { slot, render, indexMethod, ...validProps } = col
    
    // 处理筛选器方法
    if (col.filterMethod && typeof col.filterMethod === 'function') {
        validProps['filter-method'] = col.filterMethod
    }
    
    // 处理筛选器选项
    if (col.filters && Array.isArray(col.filters)) {
        validProps.filters = col.filters
    }
    
    // 处理多选筛选
    if (col.filterMultiple !== undefined) {
        validProps['filter-multiple'] = col.filterMultiple
    }
    
    // 处理可筛选属性
    if (col.filterable !== undefined) {
        validProps.filterable = col.filterable
    }
    
    return validProps
}

function handleTableScroll(e) {
    const target = e.target
    if (target.scrollHeight - target.scrollTop - target.clientHeight < 2) {
        emit('loadScroll')
    }
}

onMounted(() => {
    nextTick(() => {
        const tableInstance = elTableRef.value
        if (tableInstance && tableInstance.$el) {
            bodyWrapper = tableInstance.$el.querySelector('.el-table__body-wrapper')
            if (bodyWrapper) {
                bodyWrapper.addEventListener('scroll', handleTableScroll)
            }
        }
    })
})

onBeforeUnmount(() => {
    if (bodyWrapper) {
        bodyWrapper.removeEventListener('scroll', handleTableScroll)
    }
})

function onSelectionChange(val) {
    if (isSingleSelecting.value) {
        isSingleSelecting.value = false
        return
    }
    if (props.single && val.length > 1) {
        const last = val[val.length - 1]
        nextTick(() => {
            isSingleSelecting.value = true
            elTableRef.value.clearSelection()
            elTableRef.value.toggleRowSelection(last, true)
            selectedRows.value = [last]
            emit('selection-change', [last])
        })
    } else {
        selectedRows.value = val
        emit('selection-change', val)
    }
}
function onCurrentChange(val) {
    emit('current-change', val)
}
function onSortChange(val) {
    emit('sort-change', val)
}
function onFilterChange(val) {
    emit('filter-change', val)
}
function getRowClassName({ rowIndex }) {
    return rowIndex % 2 === 1 ? 'custom-stripe-row' : ''
}

// 暴露表格实例方法
const clearSelection = () => {
    elTableRef.value?.clearSelection()
}

const toggleRowSelection = (row, selected) => {
    elTableRef.value?.toggleRowSelection(row, selected)
}

const toggleAllSelection = () => {
    elTableRef.value?.toggleAllSelection()
}

const toggleRowExpansion = (row, expanded) => {
    elTableRef.value?.toggleRowExpansion(row, expanded)
}

const setCurrentRow = (row) => {
    elTableRef.value?.setCurrentRow(row)
}

const clearSort = () => {
    elTableRef.value?.clearSort()
}

const clearFilter = (columnKeys) => {
    elTableRef.value?.clearFilter(columnKeys)
}

const doLayout = () => {
    elTableRef.value?.doLayout()
}

const sort = (prop, order) => {
    elTableRef.value?.sort(prop, order)
}

// 暴露给父组件使用
defineExpose({
    clearSelection,
    toggleRowSelection,
    toggleAllSelection,
    toggleRowExpansion,
    setCurrentRow,
    clearSort,
    clearFilter,
    doLayout,
    sort,
    elTableRef
})
</script>

<style scoped lang="scss">
.table-container {
    height: 100%;
}

.el-table {

    ::v-deep .el-table__body-wrapper {
        padding-bottom: 0px;
    }

    // 滚动条
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
        width: 8px;
        height: 8px;
        background: transparent;
    }

    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
        background: linear-gradient(90deg, #8e8e90 0%, #6ad1ff 100%);
        border-radius: 8px;
        min-height: 30px;
        box-shadow: 0 2px 6px rgba(57, 137, 252, 0.15) inset;
        transition: background 0.3s;
    }

    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(90deg, #6ad1ff 0%, #8e8e90 100%);
    }

    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
        background: #f4f6fa;
        border-radius: 8px;
    }

    ::v-deep .el-table__body-wrapper {
        scrollbar-width: thin;
        scrollbar-color: #8e8e90 #f4f6fa;
    }
}

.el-table .el-table__cell {
    white-space: nowrap;
}

.el-table .no-wrap-cell {
    white-space: nowrap;
}

// 自定义表头样式
.custom-header-cell {
    background-color: v-bind(headerBackgroundColor) !important;
    color: v-bind(headerTextColor) !important;
    font-weight: 600 !important;
}

// 自定义斑马纹样式
::v-deep .custom-stripe-row {
    background-color: v-bind(stripeColor) !important;
}

// 表格圆角优化
::v-deep .el-table {
    border-radius: 10px;
    overflow: hidden;
}

::v-deep .el-table__header-wrapper {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
}

::v-deep .el-table__body-wrapper {
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
}

::v-deep .el-checkbox{
    display: block !important;
}   
</style>


<style lang="scss">
// 页面级别的筛选器样式，确保生效
::v-deep .el-table-filter {
    .el-table-filter__checkbox-group {
        display: flex !important;
        flex-direction: column !important;
        padding: 10px 0 !important;
        gap: 0 !important;
        
        .el-checkbox {
            display: block !important;
            margin: 0 !important;
            padding: 6px 12px !important;
            border-radius: 6px !important;
            transition: all 0.2s ease !important;
            background: transparent !important;
            
            &:hover {
                background-color: #f0f8ff !important;
            }
            
            .el-checkbox__label {
                font-size: 14px !important;
                color: #606266 !important;
                line-height: 1.4 !important;
            }
        }
    }
    
    .el-table-filter__wrap {
        min-width: 200px !important;
        max-width: 200px !important;
        padding: 0 !important;
        background: #fff !important;
        border-radius: 8px !important;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
    }
}

// 筛选图标样式 - 让图标更大更明显
::v-deep .el-table__column-filter-trigger {
    color: #909399 !important;
    font-size: 20px !important; // 增大图标尺寸
    cursor: pointer !important;
    transition: all 0.3s ease !important;
    margin-left: 3px !important;
    &:hover {
        color: #409eff !important;
        transform: scale(1.2) !important; // 悬停时放大
    }
    
    &.el-table__column-filter-trigger--active {
        color: #409eff !important;
        position: relative !important;
        
        &::after {
            content: '' !important;
            position: absolute !important;
            top: -2px !important;
            right: -2px !important;
            width: 6px !important;
            height: 6px !important;
            background: #f56c6c !important;
            border-radius: 50% !important;
            border: 1px solid #fff !important;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2) !important;
        }
    }
}

::v-deep .el-table__column-filter-trigger i{
    position: relative !important;
    top: 3px !important;
    font-size: 18px !important;
}

// 表头筛选按钮样式
::v-deep .el-table th.is-filterable {
    position: relative !important;
    
    .el-table__column-filter-trigger {
        opacity: 0.7 !important;
        transition: all 0.3s ease !important;
        
        &:hover {
            opacity: 1 !important;
        }
    }
    
    &:hover .el-table__column-filter-trigger {
        opacity: 1 !important;
    }
}
</style>